% rc9 Feb-2011 - 
%  data quality checks - b_norm, e_zero, esum, e_avg & e_03d
%
% $Id: e_avg.m 320 2005-05-05 20:07:09Z odellj $
% e_avg.m - function version of eros_avg2.m; average (e.g. /n) eros data per .sto timing info
%
% Ed Maclin eros_avg 12/11/02; e_avg 3/5/03
% $Log: e_avg.m,v $
% Revision 1.12  2004/09/01 13:55:03  edmaclin
% oops! reeset outfile test...
%
% Revision 1.11  2004/09/01 13:42:53  edmaclin
% fixed outfile test (was (if < 0))
%
% Revision 1.10  2004/08/26 19:06:16  odellj
% Fixed with inputed out_path, in_path variables to allow for averaging of norm data.
%
% Revision 1.9  2004/08/25 22:12:33  odellj
% Added the ability to pass the id_tag into the id_tags structure if this routine is called.
%
% Revision 1.8  2004/07/15 17:43:25  edmaclin
% fclose 'all', not specific fids (which may not exist)
%
% Revision 1.7  2004/07/14 19:17:01  odellj
% Typos.
%
% Revision 1.6  2004/07/13 22:26:38  odellj
% Added the new variable _id to the subprogram to output to the inidiviually created files to identify the version of the producing function.
%
% Revision 1.5  2004/07/09 21:50:14  odellj
% Updated the logging of the subroutines.  Added log_file as a parameter for each of their calls.
%
% Revision 1.4  2004/07/07 18:07:53  odellj
% Prepped for logging.
%
% Revision 1.3  2004/07/06 20:25:27  edmaclin
% Fixed merged issues
%
% Revision 1.2  2004/06/30 18:13:48  odellj
% Added more verbose fprintf statements.
%
% Revision 1.1.1.1  2004/02/18 20:09:49  odellj
% initial import into CVS
%
% Revision 1.2  2004/02/05 20:42:16  odellj
% Added Id and Log tags.
%

function e_avg(in_path,out_path,log_file)
global hdr file_name i_block dc ac ph adc aac aph n2 ssdc ssac ssph
global SDdc SDac SDph good_chs event
global nir_ph nir_ac nir_dc msg zap_flg mrac mrdc id_tags avg_PathName

fprintf('e_avg\n');

e_avg_id = '$Id: e_avg.m 320 2005-05-05 20:07:09Z odellj $';
check = strcmp(e_avg_id,id_tags); % Make sure we don't already have the tag
if sum(check) == 0
    id_tags{size(id_tags,1)+1,1} = e_avg_id;  % Add it in then.
end

% in_path=[hdr.data_path hdr.exp_name hdr.data_type hdr.hi '-' hdr.lo '\'];
% out_path=[hdr.data_path hdr.exp_name hdr.data_type hdr.hi '-' hdr.lo '\'];

% Determine whether input and output files exist
%  !!! 'exist' function doesn't work in compiler :-(
%
k=findstr('.',file_name);
out_file_name=[file_name(1:k(1)) 'avm'];
nir_file_name=[file_name(1:k(1)) 'nir'];
out_file_flg=fopen([avg_PathName '\' out_file_name]);
fclose('all');

% Open the log file if it exists
%
if ~strcmp(log_file,'')
    logid = fopen(log_file,'a');
else logid = 1; end

% fprintf(logid,'%s flag=%2.0f\n',[out_path out_file_name],out_file_flg)

% pre-allocate SD arrays for speed and to ensure full array size (n_chans)
%
SDdc=zeros(hdr.avg_baseline+hdr.epoch_length,hdr.n_chans,hdr.n_conds);
SDac=zeros(hdr.avg_baseline+hdr.epoch_length,hdr.n_chans,hdr.n_conds);
SDph=zeros(hdr.avg_baseline+hdr.epoch_length,hdr.n_chans,hdr.n_conds);

if out_file_flg < 0 % if out_file does NOT exist...
                
    % Normalize and save block averages if they exist
    %
    hdr_nir=hdr;
    if exist('nir_ph','var')
        nir_ph=nir_ph/hdr.n_blocks;
        nir_ac=nir_ac/hdr.n_blocks;
        nir_dc=nir_dc/hdr.n_blocks;
    %     fprintf(logid,'Writing %s\n\n',[out_path nir_file_name]);
        save([avg_PathName '\' nir_file_name],'nir_ph','nir_ac','nir_dc','hdr_nir','id_tags','-mat');
    end % nir_ exists
    
    % Compute Std Dev & average of event related epochs
    %
    fprintf(logid,'Computing Standard Deviations and averages...\n');

    for i_cond=1:hdr.n_conds
        for i_chan=1:hdr.n_chans
            if n2(i_chan,i_cond)~=0
                n=n2(i_chan,i_cond);
                ss=ssdc(:,i_chan,i_cond);
                sum2=adc(:,i_chan,i_cond);
                SDdc(:,i_chan,i_cond)=sqrt(abs((ss-sum2.^2/n)/n));
                
                ss=ssac(:,i_chan,i_cond);
                sum2=aac(:,i_chan,i_cond);
                SDac(:,i_chan,i_cond)=sqrt(abs((ss-sum2.^2/n)/n));
                
                ss=ssph(:,i_chan,i_cond);
                sum2=aph(:,i_chan,i_cond);                        
                SDph(:,i_chan,i_cond)=sqrt(abs((ss-sum2.^2/n)/n));
            
                adc(:,i_chan,i_cond)=adc(:,i_chan,i_cond)/n; 
                aac(:,i_chan,i_cond)=aac(:,i_chan,i_cond)/n;
                aph(:,i_chan,i_cond)=aph(:,i_chan,i_cond)/n;   
            end
        end
    end 
                
    % Write out "averages" and Std Devs in .mat format
    %
    if ~exist('hdr_norm','var');hdr_norm=[];end % create null var if needed
    if ~exist('hdr_pc','var');hdr_pc=[];end % create null var if needed
    if ~exist('hdr_filt','var');hdr_filt=[];end % create null var if needed
    hdr_avg=hdr;    % save hdr WITH UNIQUE NAME !
    msg=sprintf('Writing %s\n',[avg_PathName '\' out_file_name]);
    fprintf(logid,'Writing %s\n',[avg_PathName '\' out_file_name]);
%     history=hdr; % copy header and save with data
    save([avg_PathName '\' out_file_name],'adc','aac','aph','n2',...
        'SDdc','SDac','SDph','id_tags','event',...
        'hdr_norm','hdr_pc','hdr_filt','hdr_avg','-mat');
    fprintf(logid,'Saving %s\n',[avg_PathName '\' out_file_name]);

else    % Out_file exists
    msg=sprintf('%s already exists!\n',[avg_PathName '\' out_file_name]);
    fprintf(logid,'%s already exists!\n',[avg_PathName '\' out_file_name]);
end

if logid ~= 1, fclose(logid); end
fprintf('end e_avg\n');
